package com.dodo.blog.ui.ajax;

import com.dodo.blog.RequestCycle;
import com.dodo.blog.ui.ajax.annotation.GetModel;
import com.dodo.blog.ui.page.Page;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author <a href="mailto:pohorelec@comvai.com">Jozef Pohorelec</a>
 */
public class FormGetAjaxRequestHandler
        extends AbstractAjaxRequestHandler
{
    private static final long serialVersionUID = 1L;

    @Override
    public void handle() throws Exception
    {
        HttpServletRequest httpRequest = RequestCycle.get().getRequest();
        HttpServletResponse httpResponse = RequestCycle.get().getResponse();

        String modelId = httpRequest.getParameter( AjaxListenerHelper.PARAM_MODEL_ID );
        if ( modelId != null )
        {
            Page page = RequestCycle.get().getInjector().getInstance( getPageClass() );
            Object model = getModelObject( page, modelId );
            if ( model != null )
            {
                Response response = new Response();
                response.setMessages( RequestCycle.get().getMessages() );
                response.setModel( model );

                httpResponse.getWriter().write( MAPPER.writeValueAsString( response ) );

                return;
            }

            log.severe( "No method with annotation " + GetModel.class.getName() + "(name = '" + modelId + "') found in class " + page.getClass().getName() );
        }
    }
}
